<template>
  <AddressForm ref="form" type="adder">
    <template v-slot:navbar>
      <uni-nav-bar title="预约地址" color="#333" left-icon="left" @clickLeft="navBack" statusBar></uni-nav-bar>
    </template>
    <view class="card flex-jcsb flex-vcenter">
      <view style="font-size: 32rpx">添加为常驻地址</view>
      <view>
        <switch color="#2295ff" @change="onSwitchChange" />
      </view>
    </view>
    <view class="flex-center btn" @click="confirm">确认</view>
  </AddressForm>
</template>

<script setup lang="ts">
import { useAddressStore } from '@/stores/address';
import { getDriverID } from '@/stores/driverID';
import { navBack } from '@/utils/navigator';
import { errorToast, showLoading, successToast } from '@/utils/prompt';
import AddressForm from '@c/address/AddressForm.vue';
import { toPublish } from '@mqtt';
import { ref } from 'vue';
// static
const driver_id = getDriverID();
const addressStore = useAddressStore();
// data
let checked = false;
const repeat = ref(true); //放重复点击
function onSwitchChange() {
  checked = !checked;
}

// refs
const form = ref(null);

function confirm() {
  if (form.value.checkForm()) {
    checked ? add() : backToForm();
  }
}

function add() {
  showLoading('正在添加常驻地址');
  if (!repeat.value) {
    return;
  }
  repeat.value = false;
  const payload = {
    driver_id,
    ...form.value.getAddressInfo(),
  };
  toPublish('driver/addAddress', payload, (obj: any) => {
    const { code } = obj;
    if (code === 1) {
      repeat.value = true;
      successToast('常驻地址添加成功');
      addressStore.getList();
      backToForm();
    } else {
      repeat.value = true;
      errorToast('常驻地址添加失败');
    }
  });
}

function backToForm() {
  const addr = form.value.getAddressInfo();
  const info = {
    location: addr.abbreviate,
    address: addr.address,
    latitude: addr.latitude,
    longitude: addr.longitude,
    consignee: addr.consignee,
    phone: addr.phone,
  };
  addressStore.setDeliveryInfo(info);
  navBack({ delta: 2 });
}
</script>

<style scoped lang="less">
.card {
  margin-top: 20rpx;
  box-sizing: border-box;
  padding: 20rpx 30rpx;
  width: 95%;
  background: white;
  border-radius: 5px;
  box-shadow: 0rpx 0rpx 51rpx 0rpx rgba(179, 179, 179, 0.25);
}
.btn {
  margin-top: 366rpx;
  width: 370rpx;
  height: 80rpx;
  font-size: 36rpx;
  color: white;
  background: linear-gradient(104deg, #41a3ff, #1b91ff);
  border-radius: 5px;
}
</style>
